<template>
  <div id="uploadSingleFile" :class="[disabled ? 'is_disabled' : 'is_valid', progressFlag ? 'showProgress' : '']">
    <el-upload
      v-loading="loading"
      ref="fileUpload"
      :headers="httpHeader"
      :disabled="disabled"
      :before-upload="beforeAvatarUpload"
      :data="{batchId: batchId}"
      :http-request="uploadFile"
      :show-file-list="false"
      action="#"
      list-type="picture-card">
      <div v-show="progressFlag" class="head-img">
        <el-progress :percentage="parseInt(progressPercent)" :width="80" type="circle" color="#3E84E9"/>
      </div>
      <template v-if="!progressFlag">
        <span v-if="imageClass" :class="imageClass" class="img"/>
        <i v-else class="el-icon-plus avatar-uploader-icon"/>
      </template>
    </el-upload>
  </div>
</template>
<script type="text/javascript">
// eslint-disable-next-line no-unused-vars
import { crmFileSaveUrlOss, crmFileOssSave, getProgressPercent } from '@/api/common'
import { fileSize, timekeep } from '@/utils/index'
import axios from 'axios'
import {
  guid
} from '@/utils'
import {
  isArray, isObject
} from '@/utils/types'

const newVar = {
  name: 'uploadSingleFile', // 新建 file  一次只能上传一个文件
  props: {
    value: {
      type: [Array, Object],
      default: () => {
        return []
      }
    },
    /** 索引值 用于更新数据 */
    index: Number,
    /** 包含数据源 */
    item: Object,
    disabled: {
      type: Boolean,
      default: false
    },
    perType: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      batchId: guid(), // 批次ID
      dialogImageUrl: '',
      fileLimit: 1,
      fileType: '',
      imageClass: '',
      loading: false,
      classList: {
        'pdf': 'img_pdf',
        'ppt': 'img_ppt',
        'img': 'img_img',
        'excel': 'img_excel',
        'txt': 'img_txt',
        'word': 'img_word',
        'video': 'img_video',
        'zip': 'img_zip',
        'default': 'img_unknown'
      },
      time: '0:10',
      size: '',
      showFileLIst: [],
      progressFlag: false,
      progressPercent: 0,
      file: {}
    }
  },
  watch: {
    value: {
      handler(val) {
        if ((isArray(val) && !val.length) || (isObject(val) && !Object.keys(val).length)) {
          return
        }
        var url = val.url
        this.getFileType(url.substring(url.length - 3))
        if (this.fileType in this.classList) {
          this.imageClass = this.classList[this.fileType]
        } else {
          this.imageClass = this.classList.default
        }
      },
      immediate: true
    }
  },
  computed: {
    crmFileSaveUrlOss() {
      return crmFileSaveUrlOss
    },
    httpHeader() {
      return {
        'Admin-Token': axios.defaults.headers['Admin-Token']
      }
    }
  },
  mounted() {
  },
  methods: {
    // 限制文件格式
    beforeAvatarUpload(file) {
      this.size = fileSize(file.size)
      const isLt2M = file.size / 1024 / 1024 > 500
      if (isLt2M) {
        this.$message.error('上传文件大小不能超过500M!')
        return false
      }
      this.getFileType(file.type.split('/')[1])
      if (this.perType.indexOf(this.fileType) > -1) {
        return true
      }
      this.$message.error('上传文件格式只能是pdf或视频!')
      return false
    },
    getFileType(type) {
      this.fileType = type.toString().toLocaleLowerCase()
      if (this.fileType == 'jpeg' || this.fileType == 'jpg' || this.fileType == 'png') {
        this.fileType = 'img'
      }
      if (this.fileType == 'mp4' || this.fileType == 'mp3' || this.fileType == 'wmv' || this.fileType == 'avi' || this.fileType == 'dat' || this.fileType == 'mkv' || this.fileType == 'flv' || this.fileType == 'vob') {
        this.fileType = 'video'
      }
      if (this.fileType == 'pptx' || this.fileType.startsWith('pp')) {
        this.fileType = 'ppt'
      }
      if (this.fileType == 'doc' || this.fileType == 'docx') {
        this.fileType = 'word'
      }
      if (this.fileType == 'xls' || this.fileType == 'xlsx') {
        this.fileType = 'excel'
      }
    },
    getVideoDuration(response) {
      this.loading = true
      var url = response.url
      var video = document.createElement('video')
      video.preload = 'metadata'
      var vm = this
      video.onloadedmetadata = function() {
        window.URL.revokeObjectURL(video.src)
        vm.loading = false
        vm.time = timekeep(video.duration)
        vm.$emit('value-change', {
          index: vm.index,
          batchId: vm.batchId,
          value: response,
          time: vm.time,
          size: vm.size,
          isVideo: true
        })
      }
      video.src = url
    },
    uploadFile(data) {
      var file = data.file
      var vm = this
      this.progressFlag = true
      crmFileOssSave({
        type: file.type,
        file: file,
        batchId: vm.batchId
      }, {
        timeout: 600000,
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        onUploadProgress: progressEvent => {
          // progressEvent.loaded:已上传文件大小
          // progressEvent.total:被上传文件的总大小
          vm.progressPercent = (progressEvent.loaded / progressEvent.total * 50)
        }
      }).then(res => {
        vm.progressPercent = 50
        vm.getPercent(res.uuid)
      }).catch(res => {
        this.progressFlag = false
        this.progressPercent = 0
      })
    },
    getPercent(uuid) {
      var vm = this
      setTimeout(function() {
        getProgressPercent({ uuid: uuid }).then((res) => {
          if (res.data != null) {
            if (res.data.hasOwnProperty('url')) {
              vm.file['url'] = res.data.url
            }
            vm.progressPercent = 50 + (res.data.count / res.data.total * 50)
          }
          if (res.data.code === 1 && res.data.count === res.data.total) {
            vm.progressFlag = false
            vm.progressPercent = 0
            vm.imgFileUploadSuccess(vm.file)
            return vm.file
          }
          if (res.data.code === 0) {
            vm.progressFlag = false
            vm.progressPercent = 0
            vm.$message('上传失败！', { type: 'warning' })
            return false
          }
          vm.getPercent(uuid)
        })
      }, 3000)
    },
    // 上传文件
    imgFileUploadSuccess(response) {
      if (this.fileType in this.classList) {
        this.imageClass = this.classList[this.fileType]
      } else {
        this.imageClass = this.classList.default
      }
      if (this.fileType == 'video') {
        this.getVideoDuration(response)
      } else {
        this.$emit('value-change', {
          index: this.index,
          batchId: this.batchId,
          value: response,
          time: '0:10:10',
          size: this.size
        })
      }
    }
  }
}
export default newVar
</script>
<style lang="scss">
  .showProgress .el-upload--picture-card {
    border: 0;
    .el-progress-circle__path {
      fill:(#f5f6f9 !important);
    }
  }
  #uploadSingleFile .el-upload--picture-card {
    width: 80px;
    height: 80px;
    line-height: 78px;
    .img {
      width: 60px;
      height: 78px;
      display: inline-block;
      background:#fff url("../../assets/img/system/kms/file_unknown_big.png") no-repeat center;
      background-size: 100% 100%;
      &.img_pdf {
        background-image: url("../../assets/img/system/kms/file_pdf_big.png");
        background-size: 100% 100%;
      }
      &.img_ppt {
        background-image: url("../../assets/img/system/kms/file_ppt_big.png");
        background-size: 100% 100%;
      }
      &.img_img {
        background-image: url("../../assets/img/system/kms/file_img_big.png");
        background-size: 100% 100%;
      }
      &.img_excel {
        background-image: url("../../assets/img/system/kms/file_excle_big.png");
        background-size: 100% 100%;
      }
      &.img_txt {
        background-image: url("../../assets/img/system/kms/file_txt_big.png");
        background-size: 100% 100%;
      }
      &.img_word {
        background-image: url("../../assets/img/system/kms/file_word_big.png");
        background-size: 100% 100%;
      }
      &.img_video {
        background-image: url("../../assets/img/system/kms/file_video_big.png");
        background-size: 100% 100%;
      }
      &.img_zip {
        background-image: url("../../assets/img/system/kms/file_zip_big.png");
        background-size: 100% 100%;
      }
      &.img_default {
        background-image: url("../../assets/img/system/kms/file_unknown_big.png");
        background-size: 100% 100%;
      }
    }
  }
  #uploadSingleFile .el-upload-list--picture-card .el-upload-list__item {
    width: 80px;
    height: 80px;
  }

  #uploadSingleFile.is_disabled .el-upload--picture-card {
    background-color: #F5F7FA;
    border-color: #E4E7ED;
    color: #C0C4CC;
    cursor: not-allowed;
  }
</style>
